<!DOCTYPE html>
<html lang="en">
<head>
    <!--个人设置页面 -->
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link rel="shortcut icon" href="images/icon.ico" type="/image/x-icon"/>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
            crossorigin="anonymous"></script>
    <link rel="stylesheet" href="css/main.css">
    <title>File - Orders Management Display System</title>
</head>
<body>
<main>
    <div class="d-flex flex-column flex-shrink-0 p-3 bg-light" data-bs-scroll="true" data-bs-backdrop="false"
         tabindex="-1" style="width: 20%;min-width: 150px">
        <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto link-dark text-decoration-none">
            <span class="fs-4">Orders Management Display System</span>
        </a>
        <hr>
        <ul class="nav nav-pills flex-column mb-auto">
            <li class="nav-item">
                <a href="overview.html" class="nav-link link-dark" aria-current="page">
                    Overview
                </a>
            </li>
            <li>
                <a href="account.html" class="nav-link link-dark">
                    Accounts
                </a>

            <li>
                <a href="manage.html" class="nav-link link-dark">
                    All Orders
                </a>
            </li>

            <li>
                <a href="query.html" class="nav-link link-dark">
                    Orders Query
                </a>
            </li>
            <li>
                <a href="echarts.html" class="nav-link link-dark">
                    Chart Display
                </a>
            </li>
            <li>
                <a href="file.html" class="nav-link active">
                    File
                </a>
            </li>
        </ul>
        <hr>
        <div class="dropdown">
            <a href="#" class="d-flex align-items-center link-dark text-decoration-none dropdown-toggle" id="dropdownUser2" data-bs-toggle="dropdown" aria-expanded="false">
                <strong id="user_name_text"></strong>
            </a>
            <ul class="dropdown-menu text-small shadow" aria-labelledby="dropdownUser2">
                <li><a class="dropdown-item" href="setting.html">Settings</a></li>
                <li><hr class="dropdown-divider"></li>
                <li class="dropdown-item" id="logout">
                    Logout
                </li>
            </ul>
            <script type="text/javascript">
                const logoutButton = document.getElementById('logout')
                logoutButton.addEventListener("click", function () {
                    const request = new XMLHttpRequest()
                    request.onreadystatechange = function () {
                        if (request.readyState === 4 && request.status === 200) {
                            const json = JSON.parse(request.responseText)
                            if (json.errorCode !== "00000") {
                                alert(json.message)
                            }
                            window.location.href = "/"
                        } else if (request.readyState === 4 && request.status !== 200) {
                            alert(request.status)
                        }
                    }

                    request.open("POST", "/api/user/logout", true)
                    request.send()
                })

                function sendCurrent() {
                    const request = new XMLHttpRequest()
                    const usernameText = document.getElementById('user_name_text')
                    request.onreadystatechange = function () {
                        if (request.readyState === 4 && request.status === 200) {
                            const json = JSON.parse(request.responseText)
                            if (json.errorCode !== undefined) {
                                alert(json.message)
                                window.location.href = "/"
                                return
                            }
                            usernameText.innerHTML = json.username
                        } else if (request.readyState === 4 && request.status !== 200) {
                            alert(request.status)
                        }
                    }

                    request.open("POST", "/api/user/current", true)
                    request.send()
                }
            </script>
        </div>
    </div>
    <div class="d-flex flex-column p-4 allow-rolling">
        <div class="flex-column">
            <h1>File</h1>
        </div>
        <div class="d-inline-flex flex-row ">
            <div class="d-flex flex-column text-lg-start">
                <h2 class="flex-column">Introduction</h2>
                <div class="dropdown-divider"></div>
                <p class="flex-row">Here you can download or upload the file to the server, and the list content in the
                    file will be parsed and uploaded to the database. The downloaded files are also from the database
                    and will be saved in CSV format.<br><br></p>
                <div class="alert alert-warning">
                    <strong>Note: the uploaded file must be in CSV format, otherwise it will not be parsed. </strong>
                </div>
            </div>

        </div>
        <div class="d-flex flex-row p-2" style="min-width: 20%">
            <div class="flex-column">
                <div class="flex-column list-group">
                    <button type="button" class="list-group-item list-group-item-action" data-bs-toggle="modal"
                            data-bs-target="#file_upload">Upload file
                    </button>
                    <a class="list-group-item list-group-item-action" href="/api/file/download?target=user"
                       target="_blank">Download Users File</a>
                    <a class="list-group-item list-group-item-action" href="/api/file/download?target=order"
                       target="_blank">Download Orders File</a>
                </div>
            </div>
        </div>
        <br>
        <div class="d-flex flex-column p-2">
            <h2 class="flex-row">Files Action</h2>
            <hr>
            <button type="button" class="btn btn-outline-danger mt-2" data-bs-toggle="modal"
                    data-bs-target="#file_delete_all">Clear All Uploaded Files
            </button>
            <br>
            <h2>File List</h2>
            <div class="d-flex flex-row">
                <div class="flex-grow-1">
                    <ul class="nav nav-pills mb-3" id="file_list_tab" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="pills_list_upload" data-bs-toggle="pill"
                                    data-bs-target="#file_list_upload" type="button" role="tab"
                                    aria-controls="pills-home" aria-selected="true">Uploaded Files
                            </button>
                        </li>
                    </ul>
                    <div class="tab-content" id="file_list_content">
                        <div class="tab-pane fade show active" id="file_list_upload" role="tabpanel"
                             aria-labelledby="pills_list_upload">
                            <table class="table table-hover">
                                <caption>All Uploaded Files</caption>
                                <thead class="table table-hover">
                                <tr>
                                    <th>Path</th>
                                    <th>Size</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                                <tbody id="file-table-body">
                                </tbody>
                                <script type="text/javascript">
                                    window.onload = function () {
                                        sendCurrent()
                                        refreshFile()
                                    }

                                    function refreshFile() {
                                        const request = new XMLHttpRequest()
                                        const fileTableBody = document.getElementById("file-table-body")
                                        let fileInnerHtml = ""
                                        request.onreadystatechange = function () {
                                            if (request.readyState === 4 && request.status === 200) {
                                                const json = JSON.parse(request.responseText)
                                                if (json.errorCode !== undefined) {
                                                    alert(json.message)
                                                    return
                                                    // 返回错误信息
                                                } // 正常获得json数组
                                                for (let i in json) {
                                                    let pathPack = json[i]
                                                    fileInnerHtml += `<tr>
                                                            <td>${pathPack.path}</td>
                                                            <td>${pathPack.size}</td>
                                                            <td> <form method="post" action="/api/hdfs/download" >
                                                                    <div class="btn-group">
                                                                        <button class="btn btn-outline-primary" type="button"
                                                                                data-bs-toggle="modal"
                                                                                data-bs-target="#file-import" data-bs-path="${pathPack.path}">Import
                                                                        </button>

                                                                               <input hidden name="path" value="${pathPack.path}">
                                                                            <button class="btn btn-outline-primary" type="submit">Download</button>

                                                                        <button type="button" class="btn btn-outline-danger"
                                                                                data-bs-toggle="modal"
                                                                                data-bs-target="#file_delete_file" data-bs-path="${pathPack.path}">Delete
                                                                        </button>
                                                                    </div>
                                                                    </form>
                                                            </td>
                                                        </tr>`
                                                }
                                                fileTableBody.innerHTML = fileInnerHtml
                                            } else if (request.readyState === 4 && request.status !== 200) {
                                                alert(`error ${request.status}`)
                                            }
                                        }

                                        request.open("POST", "/api/file/list")
                                        request.send()
                                    }
                                </script>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="file_upload">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">File Upload</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-warning">
                        The maximum size of file upload is 5M. Files that exceed the size limit cannot be uploaded.
                    </div>
                    <input class="form-control" type="file" name="file_upload" id="file_upload_input">
                </div>

                <div class="modal-footer">
                    <div class="btn-group">
                        <button type="submit" class="btn btn-primary" data-bs-dismiss="modal" id="upload-file-confirm">Confirm</button>
                        <button type="reset" class="btn btn-outline-secondary">Reset</button>
                        <button type="button" class="btn btn-outline-primary" data-bs-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="file_delete_all">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Delete All Uploaded Files</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-danger">
                        <strong>All uploaded files will be deleted and cannot be recovered!</strong>
                        <br>Please check it again!
                    </div>
                </div>

                <div class="modal-footer">
                    <div class="btn-group">
                        <button type="submit" class="btn btn-danger" id="file-delete-all-confirm" data-bs-dismiss="modal">Delete</button>
                        <button type="button" class="btn btn-outline-primary" data-bs-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div class="modal fade" id="file_delete_file">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">File Delete</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input hidden id="delete_file_path">
                    <div class="alert alert-danger">
                        The selected file will be deleted and cannot be recovered. Please check it again!
                    </div>
                    <p id="current_file_path"></p>
                </div>

                <div class="modal-footer">
                    <div class="btn-group">
                        <button type="submit" class="btn btn-danger" id="file-delete-confirm" data-bs-dismiss="modal">Delete</button>
                        <button type="button" class="btn btn-outline-primary" data-bs-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="file-import">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">File Import</h4>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-danger">
                        The program will process the contents of this file and import it into the database,
                        which may cause irreversible data overwrite.
                    </div>
                    <div class="form-floating mt-3 mb-3">
                        <input hidden id="import-file-path-input">
                        <select class="form-select" id="upload_file_form_type_select" name="file_type">
                            <option value="order">Order</option>
                            <option value="other">Other</option>
                        </select>
                        <label for="upload_file_form_type_select">Select the type of data</label>
                    </div>
                    <p id="current_file_path_read"></p>
                </div>
                <div class="modal-footer">
                    <div class="btn-group">
                        <button type="submit" class="btn btn-danger" id="file-import-confirm" data-bs-dismiss="modal">Confirm</button>
                        <button type="button" class="btn btn-outline-primary" data-bs-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

</main>

<script>
    const deleteFileModel = document.getElementById('file_delete_file');
    deleteFileModel.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const filePath = button.getAttribute('data-bs-path');
        const deleteFileInput = document.getElementById('delete_file_path');
        const pathCurrent = document.getElementById('current_file_path');
        deleteFileInput.value = filePath;

        pathCurrent.innerHTML = "Current selected file path: " + filePath;
    })

    const processFileModel = document.getElementById('file-import');
    processFileModel.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const filePath = button.getAttribute('data-bs-path');
        const deleteFileInput = document.getElementById('import-file-path-input');
        const pathCurrent = document.getElementById('current_file_path_read');
        deleteFileInput.value = filePath;

        pathCurrent.innerHTML = "Current selected file path: " + filePath;
    })

    const fileUploadConfirmButton = document.getElementById("upload-file-confirm")
    fileUploadConfirmButton.addEventListener("click", function () {
        const request = new XMLHttpRequest()
        const uploadFileInput = document.getElementById("file_upload_input")
        request.onreadystatechange = function () {
            if (request.readyState !== 4) {
                return
            }
            if (request.status === 200) {
                const json = JSON.parse(request.responseText)
                if (json.errorCode !== "00000") {
                    alert(json.message)
                }
                refreshFile()
                return
            }
            alert("error")
        }

        request.open("POST", "/api/file/upload")
        let formData = new FormData()
        formData.set("file_upload", uploadFileInput.files[0])
        request.send(formData)
    })


    const fileDeleteConfirm = document.getElementById("file-delete-confirm")
    const fileDeleteAllConfirm = document.getElementById("file-delete-all-confirm")
    const fileImportConfirm = document.getElementById("file-import-confirm")

    fileDeleteConfirm.addEventListener("click", function () {
        const request = new XMLHttpRequest()
        const deleteFileInput = document.getElementById('delete_file_path');
        request.onreadystatechange = function () {
            if (request.readyState !== 4) {
                return
            }
            if (request.status === 200) {
                const json = JSON.parse(request.responseText)
                if (json.errorCode !== "00000") {
                    alert(json.message)
                } else {
                    alert("Import success!")
                }
                refreshFile()
                return
            }
            alert("error")
        }

        request.open("POST", "/api/file/delete")
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send(`type=file&path=${deleteFileInput.value}`)
    })

    fileDeleteAllConfirm.addEventListener("click", function () {
        const request = new XMLHttpRequest()
        request.onreadystatechange = function () {
            if (request.readyState !== 4) {
                return
            }
            if (request.status === 200) {
                const json = JSON.parse(request.responseText)
                if (json.errorCode !== "00000") {
                    alert(json.message)
                }
                refreshFile()
                return
            }
            alert("error")
        }

        request.open("POST", "/api/file/delete")
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send("type=all")
    })

    fileImportConfirm.addEventListener("click", function () {
        const request = new XMLHttpRequest()
        const input = document.getElementById("import-file-path-input")
        request.onreadystatechange = function () {
            if (request.readyState !== 4) {
                return
            }
            if (request.status === 200) {
                const json = JSON.parse(request.responseText)
                if (json.errorCode !== "00000") {
                    alert(json.message)
                }
                return
            }
            alert("error")
        }

        request.open("POST", "/api/order/file")
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send(`path=${input.value}`)
    })

</script>
</body>
</html>